#include "Texture2D.h"

using namespace Graphics;

Texture2D::Texture2D(unsigned int width, unsigned int height, 
		     unsigned char *data, bool alpha, bool mipmap)
{
  glGenTextures(1, &glID);
  glBindTexture(GL_TEXTURE_2D, glID);
  if(data==NULL)
    {
      glDeleteTextures(1, &glID);
      glID = 0;
      width = 0;
      hasalpha = false;
      height = 0;
    } else
    {
      if(!alpha)
	{
	  hasalpha = false;
	  if(mipmap)
	    {
	      gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, width, height, GL_RGB,
				GL_UNSIGNED_BYTE, data);
	    }
	  else
	    {
	      glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
			   GL_UNSIGNED_BYTE, data);
	    }
      
	}
      else
	{
	  hasalpha = true;
	  if(mipmap)
	    {
	      gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, width, height, GL_RGBA,
				GL_UNSIGNED_BYTE, data);
	    }
	  else
	    {
	      glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
			   GL_UNSIGNED_BYTE, data);
	    }
	}
      if(mipmap)
	{
	  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, 
			  GL_LINEAR_MIPMAP_LINEAR);
	  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
			  GL_LINEAR);
	}
    }
}

Texture2D::~Texture2D()
{
  glDeleteTextures(1, &glID);
}

unsigned int Texture2D::ID()
{
  return glID;
}

bool Texture2D::hasAlpha()
{
  return hasalpha;
}

void Texture2D::bind()
{
  glBindTexture(GL_TEXTURE_2D, glID);
}
